package com.nuanshui.heatedloan.credit.pay;

import com.aipg.cardbin.QCardBinReq;
import com.aipg.cardbin.QCardBinRsp;
import com.aipg.idverify.IdVer;
import com.aipg.qtd.QTDReq;
import com.aipg.qtd.QTDRsp;
import com.aipg.qtd.QTDRspDetail;
import com.aipg.transquery.QTDetail;
import com.aipg.transquery.QTransRsp;
import com.aipg.transquery.TransQueryReq;
import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.credit.constant.BorrowType;
import com.nuanshui.heatedloan.credit.facade.AllinPayTransService;
import com.nuanshui.heatedloan.credit.pay.constant.PayBehaviorType;
import com.nuanshui.heatedloan.credit.pay.utils.AllinPayUtil;
import com.nuanshui.heatedloan.dubbo.DubboResponse;
import com.nuanshui.heatedloan.dubbo.DubboResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * @author zss
 * @date 2017/6/30 10:16
 * @description 1:通联支付接口对接实现类
 * 2:生产对接需要 商户号，用户名，用户密码，证书密码，商户私钥文件，通联公钥文件
 * @Since
 */
@Service(ServiceConstant.ALLINPAYTRANSSERVICE)
public class AllinPayTransServiceImpl implements AllinPayTransService {

    private static final Logger logger = LoggerFactory.getLogger(AllinPayTransServiceImpl.class);


    @Autowired
    private AllinPayTool allinPayTool;

    public PayResult payFund(PayRequest request) {

        request.setTransRequestCode(TransRequestCode.TRX_CODE_SINGLE_PAY);
        PayResult payResult = allinPayTool.execute(request);
        return payResult;
    }

    @Override
    public PayResult repayFund(PayRequest request) {
        request.setTransRequestCode(TransRequestCode.TRX_CODE_REPAY);

        PayResult payResult = allinPayTool.execute(request);
        return payResult;
    }

    public DubboResponse queryBankCard(final String acctNo) {


        DubboResponse response=null;
        PayContext context = allinPayTool.execute(TransRequestCode.TRX_CODE_BANKCARD_QUERY, new Callable<QCardBinReq>() {

            @Override
            public QCardBinReq call() throws Exception {
                QCardBinReq req = new QCardBinReq();
                req.setACCTNO(acctNo);
                return req;
            }
        });

        if(context!=null)
        {
            QCardBinRsp rsp = null;
            rsp = context.getData();

            response=new DubboResponse();
            response.setCode(DubboResponseCode.SUCCESS);
            response.setData(rsp);
        }
        else
        {
            response.setCode(DubboResponseCode.COMMON_ERROR);
        }
        return response;
    }

    public QCardBinRsp queryIdNo(final String name,final String idNo) {
        QCardBinRsp rsp = null;
        PayContext context = allinPayTool.execute(TransRequestCode.TRX_CODE_IDCARD_QUERY, new Callable<IdVer>() {

            @Override
            public IdVer call() throws Exception {
                IdVer req = new IdVer();
                req.setNAME(name);
                req.setREMARK(idNo);
                return req;
            }
        });

        if(context!=null)
        {
            rsp = context.getData();
        }
        return rsp;
    }

    @Override
    public AllinPayResponse queryTrade(final String reqSn) {

        AllinPayResponse response=null;

        PayContext context = allinPayTool.execute(TransRequestCode.TRX_CODE_TRADE_QUERY, new Callable<TransQueryReq>() {

            @Override
            public TransQueryReq call() throws Exception {

                TransQueryReq transQueryReq = new TransQueryReq();
                transQueryReq.setMERCHANT_ID(PayContext.getContext().getAipgReq().getINFO().getMERCHANT_ID());
                transQueryReq.setQUERY_SN(reqSn);
                return transQueryReq;
            }
        });

        if (context != null) {
            QTransRsp rsp = context.getData();
            response=new AllinPayResponse();
            response.setINFO(context.getAipgRsp().getINFO());

            if (rsp != null) {
                List<QTDetail> listDetail = rsp.getDetails();

                if (!CollectionUtils.isEmpty(listDetail)) {
                    QTDetail detail = listDetail.get(0);
                    response.setData(detail);
                }
            }
        }

        return response;
    }

    @Override
    public AllinPayResponse queryCompletedTrade(final String reqSn) {

        AllinPayResponse response=null;

        PayContext context = allinPayTool.execute(TransRequestCode.TRX_CODE_TRADE_COMPLETED_QUERY, new Callable<QTDReq>() {

            @Override
            public QTDReq call() throws Exception {

                QTDReq transQueryReq = new QTDReq();
                transQueryReq.setMERCHANT_ID(PayContext.getContext().getAipgReq().getINFO().getMERCHANT_ID());
                transQueryReq.setQUERY_SN(reqSn);
                return transQueryReq;
            }
        });

        if(context!=null)
        {
            response.setData(context.getAipgRsp());
            QTDRsp rsp=context.getData();
            if(rsp!=null)
            {
                List<QTDRspDetail> listDetail= rsp.getDetails();

                if(!CollectionUtils.isEmpty(listDetail))
                {
                    QTDRspDetail detail=listDetail.get(0);
                    response.setData(detail);
                }
            }
        }

        return response;
    }

    public String getPayBizType(String orderId){

        String bizType=null;

        if(SysStringUtils.isEmpty(orderId)){
            return bizType;
        }
        String type=orderId.substring(14,15);
        if((BorrowType.SINGLELOAN+"").equals(type)){
            bizType=BorrowType.SINGLELOAN+"";
        }
        //闪电贷(BorrowType.LIGHTLOAN+"")
        else if((BorrowType.LIGHTLOAN+"").equals(type)){
            bizType=BorrowType.LIGHTLOAN+"";
        }
        //分期贷INSTALLMENT
        else if((BorrowType.INSTALLMENT+"").equals(type)){
            bizType=BorrowType.INSTALLMENT+"";
        }

        return bizType;
    }

    //@Override
    public void afterSingletonsInstantiated() {
        //queryTrade("200290000018288-20170807201751943825");
        //queryCompletedTrade("200290000018288-20170807201751943825");
    }
}
